package com.example.yimai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.yimai.dto.PageResponseDTO;
import com.example.yimai.entity.News;
import com.example.yimai.mapper.NewsMapper;
import com.example.yimai.repository.NewsRepository;
import com.example.yimai.service.NewsService;
import com.example.yimai.utils.ESUtil;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class NewsServiceImpl extends ServiceImpl<NewsMapper, News> implements NewsService {


    @Autowired
    private NewsRepository newsRepository;

    @Autowired
    private ElasticsearchOperations elasticsearchOperations;


    @Override
    public PageResponseDTO<News> queryNews(String keyword, int pageNum, int pageSize) {
        try{
            //构建查询参数
            BoolQueryBuilder params = new BoolQueryBuilder();
            if(keyword == null || keyword.isEmpty())
                params = QueryBuilders.boolQuery();
            else {
                params.should(QueryBuilders.matchQuery("title", keyword));
                try{
                    LocalDate date = LocalDate.parse(keyword);
                    params.should(QueryBuilders.matchQuery("createTime", date));
                }catch (Exception e){
                    //忽略
                }
            }

            NativeSearchQuery query = ESUtil.buildQuery(pageNum, pageSize, params);
            //获取查询结果
            SearchHits<News> searchHits = elasticsearchOperations.search(query, News.class);
            //将结果解析为News数组
            List<News> newsList = searchHits.getSearchHits().stream().map(hit ->{
                News news = hit.getContent();
                return news;
            }).toList();
            //构建返回对象
            PageResponseDTO<News> results = new PageResponseDTO<>();
            results.setData(newsList);
            results.setTotal((int)searchHits.getTotalHits());
            results.setPageNum(pageNum + 1);
            results.setPageSize(pageSize);
            return results;
        }catch (Exception e){
            throw new RuntimeException("查询资讯失败"+e.getMessage());
        }
    }

    @Override
    public String addNews(String title, String content) {
        News news = new News();
        LocalDate now = LocalDate.now();
        news.setTitle(title);
        news.setContent(content);
        news.setCreateTime(LocalDate.now());
        try{
            save(news);
            newsRepository.save(news);
            return "success";
        } catch (Exception e) {
            throw new RuntimeException("添加资讯失败"+e.getMessage());
        }
    }

    @Override
    public String deleteNews(Integer id) {
        try {
            removeById(id);
            //ES同步删除
            newsRepository.deleteById(String.valueOf(id));
            return "success";
        }catch (Exception e){
            throw new RuntimeException("删除资讯失败");
        }
    }

    @Override
    public News updateNews(News news) {
        try{
            UpdateWrapper<News> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id",news.getId());

            update(news, updateWrapper);

            News updatedNews = getById(news.getId());
            //更新数据同步到ES
            newsRepository.save(updatedNews);

            return updatedNews;
        } catch (Exception e) {
            throw new RuntimeException("更新资讯失败"+e.getMessage(),e);
        }
    }

    @Override
    public List<News> getLatestNews() {
        try {
            QueryWrapper<News> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByDesc("createTime");
            queryWrapper.last("limit 5");
            return baseMapper.selectList(queryWrapper);
        }catch (Exception e){
            throw new RuntimeException("获取最新资讯失败"+e.getMessage(),e);
        }
    }
}
